#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "server.h"
#include "packet.h"

#include "controller.h"
#include "teaint.h"

int connect_to_server(char *_addr, int _port)
{
	int sock = socket(PF_INET, SOCK_STREAM, 0);
	
	if (sock < 0)
	  return sock;
	  
	struct sockaddr_in address;
	
	address.sin_family = AF_INET;
	address.sin_port = htons(_port);
	inet_aton(_addr, &address.sin_addr.s_addr);  
	
	if (connect(sock, (struct sockaddr*)&address, sizeof(address)) < 0)
	  return -1;
	  
	return sock;	  
}

int greet_with_server(int _socket, int num)
{
  struct src_pkt
  {
	unsigned char cont_lo;
	unsigned char cont_hi;
	unsigned char marker;
  } 
  src_buffer = { num & 0x00ff, (num & 0xff00) >> 8, 0x2a };

  size_t pkt_len = PACKET_LEN(sizeof(struct src_pkt));
  char pkt_buffer[pkt_len];


  if (build_packet(pkt_buffer, (unsigned char*)&src_buffer, sizeof(src_buffer), pkt_len) < 0)
  {
	printf("Invalid packet !\n");
	return -1;
  }

  printf("Write buffer:");
  dump_packet(pkt_buffer, pkt_len);
  printf("\n");
  
  if (write(_socket, pkt_buffer, pkt_len) <= 0)
  {
	printf("Error write !\n");
	return -1;
  }

  size_t in_buf_len = 256;
  char in_buffer[in_buf_len];

  memset(in_buffer, 0, in_buf_len);

  size_t read_sz = read(_socket, in_buffer, in_buf_len);

  if ( read_sz <= 0)
  {
	printf("Error read !\n");
	return -1;
  }
  
  printf("Raw read buffer:");
  dump_packet(in_buffer, read_sz);
  printf("\n");
  
  tea_decode(in_buffer, read_sz);

  printf("Dec read buffer:");
  dump_packet(in_buffer, read_sz);
  printf("\n");
    
  const unsigned char *dst = 0;
  unsigned int dst_len;
  
  if (parse_packet(in_buffer, read_sz, &dst, &dst_len) < 0)
  {
	printf("Received invalid packet !\n");
	return -1;
  }
  
  
  return 0;
}
